"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
Vue.prototype.$message = ELEMENT.Message;
new Vue({
  el: "#app",
  data: function data() {
    return {
      baseUrl: "/wycms-api",
      responseResult: "",
      loading: false,
      // 测试loading
      requestData: {
        url: "/channel/getChannelListForTree",
        method: "POST",
        headers: [{
          key: "Authorization",
          value: "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjJiMDM4OTkxLTQyNjMtNDZiMC1iZWNmLTcyZTZhMDQxY2E3YiJ9.AtTB2CdiOdKxYK8sd1e8QEwccGkTVNJvUkZzhC3Gaxw1ENm3D8O4QO2qaVC0ER_W0qJytaPkCVFIyj5XVyLB-g"
        }, {
          key: "Content-Type",
          value: "application/x-www-form-urlencoded"
        }],
        params: "siteId: 531",
        data: ""
      },
      duration: 1,
      requestsPerSecond: 1,
      interval: null
    };
  },
  methods: {
    addHeader: function addHeader() {
      this.requestData.headers.push({
        key: "",
        value: ""
      });
    },
    removeHeader: function removeHeader(index) {
      this.requestData.headers.splice(index, 1);
    },
    /*
     * @params {number} 第n次调用接口
     */
    sendRequest: function sendRequest(requestCount) {
      var _this = this;
      var _this$requestData = this.requestData,
        url = _this$requestData.url,
        method = _this$requestData.method,
        headers = _this$requestData.headers,
        params = _this$requestData.params,
        data = _this$requestData.data;
      // const startTime = performance.now();
      return new Promise(function (resolve, reject) {
        var startTime = performance.now();
        axios({
          url: _this.baseUrl + url,
          method: method,
          headers: _this.buildHeaders(headers),
          params: _this.buildParams(params),
          data: data
        }).then(function (response) {
          // console.log(response);
          var endTime = performance.now();
          var responseTime = endTime - startTime;
          var result = {
            responseTime: responseTime,
            data: response.data,
            requestCount: requestCount
          };
          resolve(result);
        }).catch(function (error) {
          console.error(error);
          reject(error);
        });
      });
    },
    buildHeaders: function buildHeaders(headers) {
      var builtHeaders = {};
      var _iterator = _createForOfIteratorHelper(headers),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var header = _step.value;
          if (header.key && header.value) {
            builtHeaders[header.key] = header.value;
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return builtHeaders;
    },
    buildParams: function buildParams(params) {
      var builtParams = {};
      if (params) {
        var paramsArray = params.split("\n");
        var _iterator2 = _createForOfIteratorHelper(paramsArray),
          _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var param = _step2.value;
            var _param$split = param.split(":"),
              _param$split2 = _slicedToArray(_param$split, 2),
              key = _param$split2[0],
              value = _param$split2[1];
            if (key && value) {
              builtParams[key.trim()] = value.trim();
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      }
      return builtParams;
    },
    startTesting1: function startTesting1() {
      var _this2 = this;
      var durationInMilliseconds = this.duration * 1000;
      var requestsPerSecond = this.requestsPerSecond;
      this.responseResult = "";
      this.interval = setInterval(function () {
        for (var i = 0; i < requestsPerSecond; i++) {
          _this2.sendRequest(i + 1);
        }
      }, 1000 / requestsPerSecond);
      setTimeout(function () {
        _this2.stopTesting();
      }, durationInMilliseconds);
    },
    startTesting: function startTesting() {
      var _this3 = this;
      this.loading = true;
      var durationInMilliseconds = this.duration * 1000;
      var requestsPerSecond = this.requestsPerSecond;
      this.responseResult = "";
      var requestCount = 0;
      var responseTimeSum = 0;
      var maxResponseTime = 0;
      var minResponseTime = Infinity;
      this.interval = setInterval(function () {
        console.log("requestCount >= requestsPerSecond * this.duration: ", requestCount >= requestsPerSecond * _this3.duration, requestCount, requestsPerSecond, _this3.duration);
        if (requestCount >= requestsPerSecond * _this3.duration) {
          _this3.stopTesting();
          return;
        }
        var startTime = performance.now();
        requestCount++;
        _this3.sendRequest(requestCount).then(function (response) {
          var endTime = performance.now();
          var responseTime = (endTime - startTime).toFixed(2);
          responseTimeSum += Number(responseTime);
          maxResponseTime = Math.max(maxResponseTime, responseTime);
          minResponseTime = Math.min(minResponseTime, responseTime);
          console.log(response);
          // const contentLength = response.headers['content-length'];
          _this3.responseResult += "请求 ".concat(response.requestCount, ", 耗时：").concat(responseTime, "毫秒 \n");
          // this.responseResult += `\n`;
          // this.responseResult += `返回结果大小：${contentLength}字节\n`;
          // this.responseResult += `返回结果：${JSON.stringify(response.data)}\n\n`;
          if (response.requestCount >= requestsPerSecond * _this3.duration) _this3.donePost(responseTimeSum, requestCount, maxResponseTime, minResponseTime);
        }).catch(function (error) {
          console.error(error);
        });
      }, 1000 / requestsPerSecond);
      // setTimeout(() => {

      // }, durationInMilliseconds);
    },
    donePost: function donePost(responseTimeSum, requestCount, maxResponseTime, minResponseTime) {
      this.responseResult += "接口测试完毕  \n";
      var averageResponseTime = (responseTimeSum / requestCount).toFixed(2) - 0;
      this.responseResult += "总请求数量：".concat(requestCount, "\n");
      this.responseResult += "平均响应时间：".concat(averageResponseTime, "毫秒\n");
      this.responseResult += "最大响应时间：".concat(maxResponseTime, "毫秒\n");
      this.responseResult += "最小响应时间：".concat(minResponseTime, "毫秒\n");
    },
    stopTesting: function stopTesting() {
      clearInterval(this.interval);
      this.loading = false;
      this.responseResult += "清空计时器  \n";
    },
    getArticle: function getArticle() {
      this.requestData.url = "/article/list";
      this.requestData.params = "showType: 2 \n pageNum: 1 \n           pageSize: 10 \n channelId: 4821 \n ";
    },
    getChannel: function getChannel() {
      this.requestData.url = "/channel/getChannelListForTree";
      this.requestData.params = "siteId: 531";
    },
    //  const { url, method, headers, params, data } = this.requestData;
    // // const startTime = performance.now();
    // return new Promise((resolve, reject) => {
    //   const startTime = performance.now();
    //   axios({
    //     url: this.baseUrl + url,
    //     method: method,
    //     headers: this.buildHeaders(headers),
    //     params: this.buildParams(params),
    //     data: data,
    //   })
    handleCopy: function handleCopy() {
      var _this$requestData2 = this.requestData,
        url = _this$requestData2.url,
        method = _this$requestData2.method,
        headers = _this$requestData2.headers,
        params = _this$requestData2.params,
        data = _this$requestData2.data;
      var str = "接口地址:".concat(url, " \n 方法:").concat(method, " \n 请求参数: \n params: ").concat(JSON.stringify(this.buildParams(params)), " \n data:").concat(data, " \n 测试结果:").concat(this.responseResult, "\n          ");
      this.handleCopyValue(str);
    },
    /**
     *
     * @param {string} text 复制的文本内容
     */
    handleCopyValue: function handleCopyValue(text) {
      var _this4 = this;
      new Promise(function (res, rej) {
        //浏览器禁用了非安全域的 navigator.clipboard 对象
        //在线上环境会报错 TypeError: Cannot read properties of undefined (reading 'writeText')
        if (!navigator.clipboard && window.isSecureContext) {
          res();
          return navigator.clipboard.writeText(text);
        } else {
          // 判断是否支持拷贝
          if (!document.execCommand("copy")) return Promise.reject();
          // 创建标签，并隐藏
          var textArea = document.createElement("textarea");
          textArea.style.position = "fixed";
          textArea.style.top = textArea.style.left = "-100vh";
          textArea.style.opacity = "0";
          textArea.value = text;
          document.body.appendChild(textArea);
          // 聚焦、复制
          textArea.focus();
          textArea.select();
          return new Promise(function (resolve, reject) {
            // 不知为何，必须写这个三目，不然copy不上
            document.execCommand("copy") ? resolve() : reject();
            textArea.remove();
            res();
          });
        }
      }).then(function () {
        console.log("已复制到剪贴板");
        _this4.$message({
          message: text + "  已复制到剪贴板",
          type: "success"
        });
      }).catch(function () {
        _this4.$message({
          message: text + "  复制失败",
          type: "error"
        });
      });
    }
  }
});